﻿using System;
using System.Linq;
using System.Data;
using System.Data.Objects;

using OnlineFamilyCalendar.Model;

namespace OnlineFamilyCalendar.Data
{
    public class OnlineFamilyCalendarEntities : ObjectContext, IOnlineFamilyCalendarEntities
    {
        private ObjectSet<FamilyMember> _familyMember;
        private ObjectSet<LoginInformation> _loginInformation;

        public OnlineFamilyCalendarEntities() : base("Name=OnlineFamilyCalendarEntities")
        {
            DefaultContainerName = "OnlineFamilyCalendarEntities";
            _loginInformation = CreateObjectSet<LoginInformation>();
            _familyMember = CreateObjectSet<FamilyMember>();            
        }

        public ObjectSet<FamilyMember> FamilyMember
        {
            get
            {
                return _familyMember;
            }
        }

        public virtual ObjectSet<LoginInformation> LoginInformation
        {
            get
            {
                return _loginInformation;
            }
        }

        IObjectSet<FamilyMember> IOnlineFamilyCalendarEntities.FamilyMember
        {
            get { return this.FamilyMember; }
        }

        IObjectSet<LoginInformation> IOnlineFamilyCalendarEntities.LoginInformation
        {
            get { return this.LoginInformation; }
        }

        public override Int32 SaveChanges(SaveOptions options)
        {
            this.DetectChanges();
            foreach (var entry in from e in this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted)
                                  where (e.IsRelationship == false) && (e.Entity != null) && (e.Entity is IValidate)
                                  select e)
            {
                switch (entry.State)
                {
                    case EntityState.Added:
                        ((IValidate)entry.Entity).Validate(ChangeAction.Insert);
                        break;
                    case EntityState.Modified:
                        ((IValidate)entry.Entity).Validate(ChangeAction.Update);
                        break;
                    case EntityState.Deleted:
                        ((IValidate)entry.Entity).Validate(ChangeAction.Delete);
                        break;
                }
            }

            return base.SaveChanges(options & ~SaveOptions.DetectChangesBeforeSave);
        }

        void IDisposable.Dispose()
        {
        }
    }
}
